package com.example.controller;

// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.example.domain.ImageRecord;
import com.example.domain.ImageRequest;
import com.example.domain.vo.Result;
import com.example.mapper.AIToolMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/front/culture/Painting")
@Slf4j
public class PaintingController {
    @Autowired
    private AIToolMapper aiToolMapper;

    @PostMapping("/generate")
    public ResponseEntity<String> generateImage(@RequestBody ImageRequest request) {
        try {
            ImageSynthesisParam param = ImageSynthesisParam.builder()
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("wanx2.1-t2i-turbo")
                    .prompt(request.getPrompt())
                    .n(1)//生成数量
                    .seed(request.getSeed())
                    .size(request.getSize())
                    .build();

            ImageSynthesis imageSynthesis = new ImageSynthesis();
            ImageSynthesisResult result = imageSynthesis.call(param);

            // 存储图像路径到数据库
            String imageUrl = result.getOutput().getResults().get(0).get("url");

            ImageRecord record = new ImageRecord();
            record.setImageUrl(imageUrl);
            record.setDescription(request.getPrompt());
            record.setCreateUser(request.getCreateUser());
            aiToolMapper.insert(record);

            return ResponseEntity.ok(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException e) {
            log.error("Error generating image: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result imagList(Integer userId) {
        return Result.success(aiToolMapper.imagList(userId));
    }

    @DeleteMapping("/{imageUrl}")
    public Result removeImage(@PathVariable Integer imageUrl) {
        aiToolMapper.removeImage(imageUrl);
        return Result.success();
    }
}
